﻿using Shop.Collect;
using Shop.ExtendService;
using Shop.Model;
using Shop.RemoteModel.GoodsSpec.Model;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Helper;

namespace Shop.LocalEvent.GroupSpec
{
    [LocalEventName("Sync")]
    internal class SyncGoodsSku : IEventHandler<SpecGroupEvent>
    {
        private readonly IGoodsSkuCollect _GoodsSku;
        private readonly IFileService _File;
        public SyncGoodsSku (IGoodsSkuCollect sku, IFileService file)
        {
            this._File = file;
            this._GoodsSku = sku;
        }

        public void HandleEvent (SpecGroupEvent data, string eventName)
        {
            string[] specKey = null;
            if (!data.Groups.IsNull())
            {
                if (data.Groups.Length == 1)
                {
                    specKey = data.Groups[0].Spec.ConvertAll(a => a.Id.ToString().GetMd5());
                }
                else
                {
                    specKey = _GetSpecKey(data.Groups);
                }
            }
            long[] skuId = this._GoodsSku.Clear(data.GoodsId, specKey);
            if (skuId != null)
            {
                this._File.Drop(new string[]
                {
                    ShopFileDirDic.GoodsImgShow,
                    ShopFileDirDic.GoodsSkuImg,
                    ShopFileDirDic.GoodsSkuCover
                }, skuId);
            }
        }
        private static void _FormatSku (List<string> skus, GoodsSpecGroup[] groups, int index, Span<long> spacId)
        {
            int next = index + 1;
            foreach (GoodsSpec spec in groups[index].Spec)
            {
                if (next >= spacId.Length)
                {
                    long[] ids = spacId.ToArray();
                    ids[index] = spec.Id;
                    skus.Add(string.Join(',', ids.OrderBy(a => a)).GetMd5());
                }
                else
                {
                    spacId[index] = spec.Id;
                    _FormatSku(skus, groups, next, spacId);
                }
            }
        }
        private static string[] _GetSpecKey (GoodsSpecGroup[] groups)
        {
            int gLen = groups.Length;
            List<string> skus = new List<string>(20);
            groups[0].Spec.ForEach(c =>
            {
                Span<long> ids = new Span<long>(new long[gLen]);
                ids[0] = c.Id;
                _FormatSku(skus, groups, 1, ids);
            });
            return skus.ToArray();
        }
    }
}
